<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-24 20:16:02
 * @LastEditors: Andy
 * @LastEditTime: 2023-02-17 14:18:43
-->
<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="resetSearch">
      <x-filter-item :label="$t('system.user.account')">
        <el-input
          v-model="searchParams.username"
          :placeholder="$t('system.user.PleaseEnter')"
          clearable
          maxlength="100"
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('system.user.user')">
        <el-input
          v-model="searchParams.queryCondition"
          :placeholder="$t('system.user.PleaseEnter')"
          clearable
          maxlength="100"
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('system.user.onlineStatus')">
        <x-select
          :placeholder="$t('system.user.choose')"
          v-model="searchParams.onlineStatus"
          :options="dictOptions['upms_user.online_status']"
          style="width: 100%"
          clearable
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="$t('system.user.status')">
        <x-select
          :placeholder="$t('system.user.choose')"
          v-model="searchParams.state"
          :options="dictOptions['system.state']"
          style="width: 100%"
          clearable
        ></x-select>
      </x-filter-item>
      <!-- <x-filter-item :label="$t('system.user.creatTime')">
          <el-date-picker
            v-model="searchParams.times"
            end-placeholder="结束日期"
            format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            style="width: 100%"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </x-filter-item> -->
    </x-filter>
    <!--数据面板-->
    <x-data>
      <!--数据面板按钮插糟-->
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              v-hasPermi="['upms:user:add']"
              type="primary"
              @click="handleAddUser()"
              :icon="buttonIcons('add')"
            >
              {{ $t('system.user.new') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:user:state']"
              type="primary"
              @click="handleBatchUserstate('0')"
              :icon="buttonIcons('other')"
            >
              {{ $t('system.user.batchStop') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:user:state']"
              type="primary"
              @click="handleBatchUserstate('1')"
              :icon="buttonIcons('other')"
            >
              {{ $t('system.user.batchStart') }}
            </el-button>

            <el-button
              v-hasPermi="['upms:user:exportExcel']"
              type="primary"
              @click="handleExportUser()"
              :icon="buttonIcons('export')"
            >
              {{ $t('system.user.export') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:user:exportAuths']"
              type="primary"
              @click="handleExportAuth()"
              :icon="buttonIcons('export')"
            >
              {{ $t('system.user.exportUserRoles') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:user:delete']"
              type="danger"
              @click="handleBatchDelete()"
              :icon="buttonIcons('delete')"
            >
              {{ $t('system.user.batchDelete') }}
            </el-button>
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
          :minWidth="item.minWidth"
        >
          <template #default="scope">
            <el-switch
              v-if="item.prop === 'state'"
              :value="scope.row[item.prop]"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              @change="handleChangeUserState(scope.row[item.prop], scope.row.id)"
              :disabled="!checkBntPermi('upms:user:state')"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <span v-else-if="item.prop === 'workStatus'">
              {{
                scope.row[item.prop]
                  ? selectDictLabel(dictOptions['upms_user.work_status'], scope.row[item.prop] + '')
                  : '-'
              }}
            </span>
            <x-state-cell
              v-else-if="item.prop === 'onlineStatus'"
              :stateClass="scope.row[item.prop] === 0 ? 'gray' : scope.row[item.prop] ? 'success' : ''"
              :text="selectDictLabel(dictOptions['upms_user.online_status'], scope.row[item.prop] + '')"
            />
            <span v-else-if="item.prop === 'gender'">
              {{
                scope.row[item.prop] ? selectDictLabel(dictOptions['upms_user.gender'], scope.row[item.prop] + '') : '-'
              }}
            </span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="220">
          <template #default="scope">
            <more-table-actions
              :action-list="getActions(actions, scope.row)"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <user-add ref="userAddComponent" :dict-options="dictOptions" @handleSuccess="loadData"></user-add>
    <user-other-roles ref="userRoleComponent" @handleSuccess="loadData"></user-other-roles>
    <user-reset ref="userResetComponent" @handleResetSuccess="loadData"></user-reset>
  </x-page>
</template>
<script>
  // import { QueryDictMixin, TableListMixin, PermissionsMixin } from '@/common/mixins'
  import { selectDictLabel, buttonIcons, QueryDictMixin, TableListMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import { actions, columns } from '../config/userConfig.js'
  import {
    apiDeleteUser,
    apiGetUserInfo,
    apiPostbatchUserDisable,
    apiPutbatchUserEnble,
    listUrl,
    userExportUrl,
    userRoleExportUrl
  } from '../api'
  import UserAdd from '../components/userAdd.vue'
  import UserOtherRoles from '../components/userOtherRoles.vue'
  import UserReset from '../components/userReset.vue'

  import { EnumApiCode } from '../../../../../../globalEnum'

  const { login } = pinias
  export default {
    name: 'User',
    components: {
      UserAdd,
      UserOtherRoles,
      UserReset
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        userExportUrl,
        userRoleExportUrl,
        listUrl,
        columns,
        actions,
        searchParams: {
          // account: '',
          // role
          userName: '',
          // online: '',
          state: '',
          queryCondition: ''
          // times: []
        },
        tableData: [],
        dictKeys: [
          'upms_user.online_status',
          'upms_user.work_status',
          'upms_user.gender',
          'system.state',
          'upms_user.user_type'
        ]
      }
    },
    computed: {
      ...mapState(login, ['user']),
      getActions() {
        return (actions, row) => {
          const btns = actions.map((action) => {
            if (['delete', 'edit'].indexOf(action.key) !== -1 && row.preset === 1) {
              action.disabled = true
            } else {
              action.disabled = false
            }
            return action
          })
          return btns
        }
      }
    },
    beforeDestroy() {
      console.log('-------beforeDestroy------')
    },
    methods: {
      buttonIcons,
      selectDictLabel,
      handleSearch() {
        this.queryParam = JSON.parse(JSON.stringify(this.searchParams))
        this.queryParam.beginTime = this.queryParam.times ? this.queryParam.times[0] : ''
        this.queryParam.endTime = this.queryParam.times ? this.queryParam.times[1] : ''
        delete this.queryParam.times
        this.loadData()
      },

      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改用户基本信息
            apiGetUserInfo(data.id).then(({ data }) => {
              this.$refs.userAddComponent.handleOpen(data)
            })
            break
          case 'delete':
            this.handleBatchDelete(data.id)
            break
          case 'resetPassword':
            this.$refs.userResetComponent.handleOpen(data)
            break
          case 'auth': // 授权用户岗位权限
            apiGetUserInfo(data.id).then(({ data }) => {
              this.$refs.userRoleComponent.handleOpen(data)
            })
            break
          case 'authView':
            this.$router.push({ path: '/system/user/userAuth', query: { userId: data.id } })
            break
          default:
            break
        }
      },
      /**
       * 新增用户
       *
       */
      handleAddUser() {
        this.$refs.userAddComponent.handleOpen()
      },
      handleExportUser() {
        this.handleExport(this.userExportUrl)
      },
      handleExportAuth() {
        this.handleExport(this.userRoleExportUrl)
      },
      handleBatchUserstate(type, id) {
        if (!id && !this.selectionRows.length) {
          this.$message.warning('请勾选操作项！')
          return
        }
        this.$confirm(`您确定要批量${`${type}` === '1' ? '启用' : '禁用'}吗？`, this.$t('system.user.deletePrompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then((confirm) => {
            const ids = id ? [id] : this.selectionRows.map((v) => v.id)
            this.handleChangeUserState(`${type}` === '1' ? '0' : '1', ids)
          })
          .catch((cancel) => {})
      },
      async handleChangeUserState(state, ids) {
        const result = Array.isArray(ids) ? ids : [ids]
        try {
          const { code, msg } =
            `${state}` === '0' ? await apiPutbatchUserEnble(result) : await apiPostbatchUserDisable(result)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('system.user.successTips'))
          } else {
            this.$message.error(msg)
          }
          this.loadData()
        } finally {
          this.loadData()
        }
      },
      handleBatchDelete(id) {
        if (!id && !this.selectionRows.length) {
          this.$message.warning('请选择删除的用户')
          return
        }
        this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then((confirm) => {
            const ids = id || this.selectionRows.map((v) => v.id).join(',')
            this.handleDeleteUser(ids)
          })
          .catch((cancel) => {})
      },
      /**
       * 删除用户的请求
       * @param userId 用户ID string
       */
      async handleDeleteUser(userId) {
        const { code, msg } = await apiDeleteUser(userId)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.loadData()
        } else {
          this.$message.error(msg)
        }
      }
    }
  }
</script>
